package uebung04_h;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;

import tools.ColorConversions;
import tools.Derivative;
import tools.Gauss;
import tools.Image;

public class Surfy {
	
	public static void main(String[] args) {
		try {
			final BufferedImage bi = ImageIO.read(Surfy.class.getClassLoader().getResourceAsStream("res/kermit001.jpg"));
			
			int[] rgb = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), new int[bi.getWidth()*bi.getHeight()], 0, bi.getWidth());
			
			double[] lum = Image.getScalarLuminance(ColorConversions.getFastLuminance(rgb, new int[rgb.length]), new double[rgb.length]);
			
			double[] dx = Derivative.dx(lum, bi.getWidth(), bi.getHeight(), new double[rgb.length]), dy = Derivative.dy(lum, bi.getWidth(), bi.getHeight(), new double[rgb.length]);
			
			int x = 200, y = 200, windowS = 20;
			
			double scale = 2./5., sigmaF = 3.3;
			double[] descriptor = new double[64]; 
			double halfWidth = (windowS*scale)/2., step = halfWidth/2;
			int index = 0;
			
			for (double j = -halfWidth; j<halfWidth; j+=step) {
				for (double i = -halfWidth; i<halfWidth; i+=step) {
					double sumdx = 0, sumdy = 0, sumabsdx = 0, sumabsdy = 0;
					
					//For each subregion we compute a few simple features at 5x5 regularly spaced sample points. (From Wide-baseline Point and Line Correspondences to 3D, Herbert Bay, p.39 )
					for (int l = 0; l<5; l++) {
						for (int k = 0; k<5; k++) {
						
							double cx = i+step/k, cy = j+step/l, dif = Math.sqrt((cx-i)*(cx-i)+(cy-j)*(cy-j));
							double gauss = Gauss.gaussian1d(dif, sigmaF*scale);
							double dx_ = gauss*Image.bilerp(dx, cx, cy, bi.getWidth(), bi.getHeight()), dy_ = gauss*Image.bilerp(dy, cx, cy, bi.getWidth(), bi.getHeight());
							
							sumdx += dx_;
							sumdy += dy_;
							sumabsdx += Math.abs(dx_);
							sumabsdy += Math.abs(dy_);
						}
					}
					
					descriptor[index] = sumdx;
					index++;
					descriptor[index] = sumdy;
					index++;
					descriptor[index] = sumabsdx;
					index++;
					descriptor[index] = sumabsdy;
					index++;
					
				}
			}
			
			
//			JFrame ff = new JFrame();
//			ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//			
//			final JComponent canvas = new JComponent() {
//				{setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));}
//				@Override
//				public void paint(Graphics g) {
//					g.drawImage(bi, 0, 0, this);
//					super.paint(g);
//				}
//			};
//			
//			ff.add(canvas);
//			ff.pack();
//			ff.setVisible(true);
			
			System.out.println(Arrays.toString(descriptor));
		}
		catch (IOException iox ) {
			iox.printStackTrace();
		}
	
	}
}
